package com.situ.company.employee.servlet;


import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.json.JSONObject;

import com.situ.company.employee.model.EmployeeModel;
import com.situ.company.employee.service.EmployeeService;
import com.situ.company.util.FmtRequest;
import com.situ.company.util.UploadUtil;


@WebServlet("/EmployeeUpload")
public class EmployeeUploadServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	private EmployeeService service = new EmployeeService();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Map<String, Object> map = null;
		try {
			map=UploadUtil.upload(req);
		} catch (FileUploadException | IOException e) {
			e.printStackTrace();
		}
		String code = map.get("code").toString();
		EmployeeModel model = new EmployeeModel(code);
		EmployeeModel mdb = service.selectModel(model);
		String im = mdb.getImage();
		if (im != null && !im.trim().isEmpty()) {
			UploadUtil.delFile(mdb.getImage());
		}
		
		List<String> list = (List<String>) map.get("list"); 
		String image = list.get(0);
		model.setImage(image);
		String res = service.update(model);
		Map<String, String> result = new HashMap<>();
		result.put("code", res);
		result.put("image", image);
		FmtRequest.out(resp,new JSONObject(result).toString());
	}
}
